﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using WorkStation.Frameworks.Core;
using WorkStation.Frameworks.Core.Extensions;

using WorkStation.Frameworks.EasyBus.Extensions;

using Newtonsoft.Json;

namespace WorkStation.Frameworks.EasyBus
{
    /// <summary>
    /// 用于在网络中传递的消息对象
    /// </summary>
    public class Message
    {
        /// <summary>
        /// 消息唯一标识
        /// </summary>
        public string MessageId { get; set; }

        /// <summary>
        /// 路由关键字
        /// </summary>
        public string RouteKey { get; set; }

        /// <summary>
        /// 消息对象
        /// </summary>
        public string BodyJson { get; set; }

        /// <summary>
        /// 是否记录消息到记录中心（如果不记录日志，将不支持发布和处理的幂等性），默认记录
        /// </summary>
        public bool IsRecordingHistory { get; set; }

        private Message() { }

        public Message(object body) : this(null, body, null)
        {
            
        }

        public Message(object body, string routeKey) : this(null, body, routeKey)
        {
        
        }

        public Message(string messageId, object body, string routeKey) 
        {
            if (messageId.IsNullOrEmpty())
            {
                this.MessageId = Guid.NewGuid().ToString();
            }
            else 
            {
                this.MessageId = messageId;
            }

            if (routeKey.IsNullOrEmpty())
            {
                this.RouteKey = body.GetType().FullName;
            }
            else 
            {
                this.RouteKey = routeKey;
            }

            (body == null).WhenTrue(() => { throw new ArgumentNullException("body"); });

            if (body is string)
            {
                this.BodyJson = body as string;
            }
            else 
            {
                this.BodyJson = body.ObjectToJson();
            }

            this.IsRecordingHistory = true;
        }
    }
}
